package main

import (
	mymodel "attendance/model"
	"fmt"
	"log"
	"net/http"
	"os"
	"encoding/base64"

	"github.com/labstack/echo/v5"
	"github.com/pocketbase/pocketbase"
	"github.com/pocketbase/pocketbase/apis"
	"github.com/pocketbase/pocketbase/core"
	"github.com/pocketbase/pocketbase/forms"
	"github.com/pocketbase/pocketbase/models"
	"github.com/pocketbase/pocketbase/tools/filesystem"
)

func main() {
    app := pocketbase.New()

    // serves static files from the provided public dir (if exists)
    app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
        e.Router.GET("/*", apis.StaticDirectoryHandler(os.DirFS("./pb_public"), false))
        return nil
    })

	app.OnBeforeServe().Add(func(e *core.ServeEvent) error {
		e.Router.POST("/ext/record/upload", func(c echo.Context) error {
			var r mymodel.CaptureRecord
			err := c.Bind(&r)
			// bytes,_ := r.Marshal()
			// json := string(bytes)
			// fmt.Println(json)
			use(fmt.Append)
			if err != nil {
				return err
			}

			collection, err := app.Dao().FindCollectionByNameOrId("capture_record")
			if err != nil {
				return err
			}

			record := models.NewRecord(collection)
			form := forms.NewRecordUpsert(app, record)

			// set individual fields
			// or bulk load with record.Load(map[string]any{...})
			//record.Set("closeup", "Lorem ipsum")
			//record.Set("active", true)
			//record.Set("someOtherField", 123)
			closeup, _ :=  base64.StdEncoding.DecodeString(r.CloseupPic.Data)
			template, _ := base64.StdEncoding.DecodeString(r.Match.Image)
			closeupFile, _ := filesystem.NewFileFromBytes(closeup, "closeup")
			templateFile, _ := filesystem.NewFileFromBytes(template, "template") 
			form.AddFiles("closeup", closeupFile)
			form.AddFiles("template", templateFile)

			if err := form.Submit(); err != nil {
				return err
			}

			return c.JSON(http.StatusOK, map[string]string{"msg": "well done"})
		})
		return nil
	})

    if err := app.Start(); err != nil {
        log.Fatal(err)
    }
}

func use(p interface{}) {

}

